package com.yneusoft.pctask.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yneusoft.common.model.ResponseWrapper;
import com.yneusoft.common.tool.CommonTool;
import com.yneusoft.common.tool.DataProcessing;
import com.yneusoft.dao.entity.*;
import com.yneusoft.dao.mapper.*;
import com.yneusoft.pctask.mapper.ProjectManageMapper;
import com.yneusoft.pctask.model.*;
import entity.ProjectType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @Description： 项目管理service层
 * @Author: wbf
 * @Date: 2021/11/12 10:13
 */
@Service
public class ProjectManageService {
    //项目管理mapper
    @Autowired
    ProjectManageMapper projectManageMapper;
    //项目mapper
    @Autowired
    ProjectMapper projectMapper;
    //员工mapper
    @Autowired
    StaffMapper staffMapper;
    //工时mapper
    @Autowired
    ProjectWorkHourMapper projectWorkHourMapper;
    //项目类型mapper
    @Autowired
    ProjectTypeMapper projectTypeMapper;
    //项目员工mapper
    @Autowired
    ProjectStaffMapper projectStaffMapper;
    //项目状态mapper
    @Autowired
    ProjectStateMapper projectStateMapper;
    /**
     * 1.获取项目列表
     * @param param 搜索关键字 分页
     * @return 项目列表
     */
    public ResponseWrapper getProjectListResult(GetProjectListParam param){
        param.setPage(DataProcessing.CalculatePage(param.getPage(),param.getPageSize()));//计算分页
        param.setSearchKey(DataProcessing.CreatFuzzyQuery(param.getSearchKey()));//关键字处理
        List<Map<String, Object>> mapList = projectManageMapper.getProjectList(param);
        List<GetProjectList> list = CommonTool.mapListToBeanList(mapList,GetProjectList.class);//获取项目列表

        for (GetProjectList each : list) {
            each.setStaffList(CommonTool.mapListToBeanList(projectManageMapper.getStaffList(each.getAid()),ProjectNetStaff.class)); //获取每一个项目的员工列表

            /**
             * 统计项目工时
             */
            LambdaUpdateWrapper<ProjectWorkHour> getTotalWorkHour = new LambdaUpdateWrapper<>();
            getTotalWorkHour.eq(ProjectWorkHour::getProjectAid,each.getAid());
            List<ProjectWorkHour> workHours = projectWorkHourMapper.selectList(getTotalWorkHour);
            Double totalWorkHour = 0.00;
            for (ProjectWorkHour hour : workHours) {
                totalWorkHour += hour.getWorkHour();
            }
            each.setTotalWorkHour(totalWorkHour);
        }
        /**
         * 统计项目列表数据
         * "newsNum",
         * "startNum",
         * "completeNum",
         * "rowsNum"
         */
        LambdaQueryWrapper<Project> getRowsNum = new LambdaQueryWrapper<>();
        if(param.getSearchKey() != null && param.getSearchKey() != ""){
            getRowsNum.like(Project::getName,param.getSearchKey());
        }
        if(param.getId() != null){
            getRowsNum.eq(Project::getStateId,param.getId());
        }
        if(param.getId() != null) {
            getRowsNum.eq(Project::getTypeAid, param.getAid());
        }
        Integer rowsNum = projectMapper.selectCount(getRowsNum);
        StaffCountNum num = CommonTool.mapListToBeanList(projectManageMapper.getNum(),StaffCountNum.class).get(0);

        GetProjectListResult result = new GetProjectListResult(rowsNum,num.getNewsNum(),num.getStartNum(),num.getCompleteNum(),list);
        return ResponseWrapper.markSuccess(result);
    }

    /**
     * 2、修改项目状态
     * @param param 修改状态传参
     * @return 是否成功
     */
    public ResponseWrapper updateProjectState(UpdateProjectStateParam param){
        String time = DataProcessing.getFormatTime(null);
        String date = DataProcessing.getFormatTime("yyyy-MM-dd");
        /**
         * 获取参数所指定的项目
         */
        LambdaUpdateWrapper<Project> updateProjectStateWrapper = new LambdaUpdateWrapper<>();
        updateProjectStateWrapper
                .eq(Project::getAid,param.getAid())
        ;
        Project newProject = projectMapper.selectOne(updateProjectStateWrapper);
        if(newProject == null){return ResponseWrapper.markCustomSuccess("该项目不存在，请检查aid");}
        /**
         * 获取项目状态id进行判断
         */
        Integer stateId = param.getId();
        newProject.setStateId(stateId);
        if(stateId == 10){ newProject.setUpdateTime(time); }
        else if(stateId == 20){
            newProject.setUpdateTime(time);
            newProject.setStartDate(date);
        }
        else if(stateId == 30){
            newProject.setUpdateTime(time);
            newProject.setEndDate(date);
        }
        projectMapper.updateById(newProject);
        return ResponseWrapper.markSuccess();
    }

    /**
     * 3、获取项目工时明细
     * @param param 请求参数
     * @return 工时列表
     */
    public ResponseWrapper getProjectWorkHourList(GetProjectWorkHourListParam param){
        param.setPage(DataProcessing.CalculatePage(param.getPage(),param.getPageSize()));
        List<GetProjectWorkHourList> list = CommonTool.mapListToBeanList(projectManageMapper.getProjectWorkHourList(param),GetProjectWorkHourList.class);
        for (GetProjectWorkHourList each : list) {
            each.setCreatTime(each.getCreatTime().replace("T"," "));
            each.setCreatTime(DataProcessing.getFormatTime(null,each.getCreatTime()));
        }
        LambdaUpdateWrapper<ProjectWorkHour> getRowsNum = new LambdaUpdateWrapper<>();
        getRowsNum.eq(ProjectWorkHour::getProjectAid,param.getAid());
        if(param.getStartTime() != null && param.getEndTime() != null){
            getRowsNum.between(ProjectWorkHour::getUpdateTime,param.getStartTime(),param.getEndTime());
        }
        if(param.getTypeAid() != null){
            getRowsNum.eq(ProjectWorkHour::getWorkTypeAid,param.getTypeAid());
        }
        Integer rowsNum = projectWorkHourMapper.selectCount(getRowsNum);
        GetProjectWorkHourListResult result = new GetProjectWorkHourListResult(rowsNum,list);

        return ResponseWrapper.markSuccess(result);
    }

    /**
     * 4、【新增/修改】获取员工列表
     * @return 员工列表
     */
    public ResponseWrapper getStaffList(){
        LambdaUpdateWrapper<Staff> onJobWrapper = new LambdaUpdateWrapper<>();
        onJobWrapper.eq(Staff::getStateId,10);
        List<Staff> staffList = staffMapper.selectList(onJobWrapper);
        List<GetStaffListResult> results = JSON.parseArray(JSON.toJSONString(staffList)).toJavaList(GetStaffListResult.class);
        return ResponseWrapper.markSuccess(results);
    }

    /**
     * 5、【新增/修改】获取项目类型列表
     * @return 项目类型列表
     */
    public ResponseWrapper getProjectTypeList(){
        List<ProjectType> projectTypes = projectTypeMapper.selectList(null);
        List<GetProjectTypeListResult> results = JSON.parseArray(JSON.toJSONString(projectTypes)).toJavaList(GetProjectTypeListResult.class);
        return ResponseWrapper.markSuccess(results);
    }

    /**
     * 6、【新增/修改】获取项目状态列表
     * @return 项目状态列表
     */
    public ResponseWrapper getProjectStateList(){
        List<ProjectState> projectStates = projectStateMapper.selectList(null);
        List<GetProjectStateListResult> results = JSON.parseArray(JSON.toJSONString(projectStates)).toJavaList(GetProjectStateListResult.class);
        return ResponseWrapper.markSuccess(results);
    }

    /**
     * 7、【新增/修改】新增/修改项目信息
     * @param param 新增/修改参数
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper insertOrUpdateProjectInfo(InsertOrUpdateProjectInfoParam param){
        String time = DataProcessing.getFormatTime(null);
        Project newProject = JSON.parseObject(JSON.toJSONString(param),Project.class);
        Integer aid;
        LambdaUpdateWrapper<Project> getInsertAid = new LambdaUpdateWrapper<>();
        if(newProject.getAid() == -1){

            newProject.setUpdateTime(time); //项目更新时间
            newProject.setCreateTime(time); //项目创造时间
            projectMapper.insert(newProject); //新增员工
            /**
             * 获取新增后的aid
             */
            getInsertAid.eq(Project::getCreateTime,time);
            aid = projectMapper.selectOne(getInsertAid).getAid();
        }
        else {
            newProject.setUpdateTime(time); //项目更新时间
            aid = param.getAid();
            projectMapper.updateById(newProject);
        }

        //删除原有员工关系
        LambdaUpdateWrapper<ProjectStaff> deleteRelate = new LambdaUpdateWrapper<>();
        deleteRelate.eq(ProjectStaff::getProjectAid,aid);
        projectStaffMapper.delete(deleteRelate);
        //将员工列入项目名单中
        List<StaffAidList> staffAidList = param.getStaffAidList();
        for (StaffAidList each : staffAidList) {
            ProjectStaff projectStaff = new ProjectStaff(null,each.getAid(),aid,time,time);
            projectStaffMapper.insert(projectStaff);
        }

        return ResponseWrapper.markSuccess();
    }

    /**
     * 8、【新增/修改】获取修改时的项目信息
     * @param param 项目aid
     * @return 项目信息
     */
    public ResponseWrapper getProjectInfo(GetProjectInfoParam param){
        GetProjectInfoResult projectInfo = CommonTool.mapListToBeanList(projectManageMapper.getProjectInfo(param),GetProjectInfoResult.class).get(0);
        projectInfo.setStaffList(CommonTool.mapListToBeanList(projectManageMapper.getStaffList(param.getAid()),ProjectNetStaff.class));
        return ResponseWrapper.markSuccess(projectInfo);
    }
}